package com.sainthigh.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

import org.apache.http.conn.util.InetAddressUtils;

import com.sainthigh.aidl.LogUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

public class IPUtils {

	/**
	 * 01-02 03:24:10.960: W/System.err(2398): java.net.SocketException
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at java.net.NetworkInterface.rethrowAsSocketException(NetworkInterface.java:248)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at java.net.NetworkInterface.collectIpv4Address(NetworkInterface.java:208)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at java.net.NetworkInterface.getByNameInternal(NetworkInterface.java:127)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at java.net.NetworkInterface.getNetworkInterfacesList(NetworkInterface.java:309)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at java.net.NetworkInterface.getNetworkInterfaces(NetworkInterface.java:298)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at com.sainthigh.ip.IPUtils.getLocalIpAddress(IPUtils.java:28)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at com.sainthigh.ip.IPActivity.onClick(IPActivity.java:28)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at android.view.View.performClick(View.java:4438)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at android.view.View$PerformClick.run(View.java:18422)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at android.os.Handler.handleCallback(Handler.java:733)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at android.os.Handler.dispatchMessage(Handler.java:95)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at android.os.Looper.loop(Looper.java:136)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at android.app.ActivityThread.main(ActivityThread.java:5001)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at java.lang.reflect.Method.invokeNative(Native Method)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at java.lang.reflect.Method.invoke(Method.java:515)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at dalvik.system.NativeStart.main(Native Method)
	 * <br>01-02 03:24:10.960: W/System.err(2398): Caused by: libcore.io.ErrnoException: socket failed: EACCES (Permission denied)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at libcore.io.Posix.socket(Native Method)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at libcore.io.BlockGuardOs.socket(BlockGuardOs.java:181)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at java.net.NetworkInterface.collectIpv4Address(NetworkInterface.java:193)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	... 16 more
	 * <br> 这种情况，添加  <uses-permission android:name="android.permission.INTERNET" />
	 * <br>获取本地ip
	 * @return
	 */
	public static String getLocalIpAddress() {
		try {
			String ipv4 = null;
			List<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
			for(NetworkInterface ni : nilist) {
				List<InetAddress> ialist = Collections.list(ni.getInetAddresses());
				for (InetAddress address : ialist) {
					ipv4 = address.getHostAddress();
					if(!address.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipv4)) {
						return ipv4;
					}
				}
			}
		} catch(SocketException e) {
			LogUtils.stackTrace(e);
		}
		return null;
	}
	
//	public static String getLocalIpAddress() {
//		try {
//			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
//				NetworkInterface intf = en.nextElement();
//				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
//					InetAddress inetAddress = enumIpAddr.nextElement();
//					if (!inetAddress.isLoopbackAddress()) {
//						return inetAddress.getHostAddress().toString();
//					}
//				}
//			}
//		} catch (SocketException ex) {
//			LogUtils.e(ex.toString());
//		}
//		return null;
//	}

	/**
	 * <br> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission> 
	 * <br> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission> 
	 * <br> <uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>  
	 * @return
	 */
	public static final String getLocalIpAddressWIFI(Context ctx) {
		// 判断WIFI是否开启
		WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);

		//判断是否开启wifi
		if(!wifiManager.isWifiEnabled()) {
			wifiManager.setWifiEnabled(true);
		}
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		int ipAddress = wifiInfo.getIpAddress();
		String ip = (ipAddress & 0xFF ) + "." +      
				((ipAddress >> 8 ) & 0xFF) + "." +      
				((ipAddress >> 16 ) & 0xFF) + "." +      
				( ipAddress >> 24 & 0xFF) ; ;
		return ip;		
	}

//	private static String intToIp(int i) {
//		return (i & 0xFF ) + "." +      
//				((i >> 8 ) & 0xFF) + "." +      
//				((i >> 16 ) & 0xFF) + "." +      
//				( i >> 24 & 0xFF) ; 
//	}

	
	//=======================================================
	//=======================================================
	//=======================================================
	//=======================================================
	//=======================================================
	// 第一步：首先是判断网络环境
	private static void step1(Context ctx, boolean isDebug){
		String ip;
		ConnectivityManager conMann = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo mobileNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		NetworkInfo wifiNetworkInfo   = conMann.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		if(mobileNetworkInfo.isConnected()) {
			ip = getLocalIpAddress_step2(isDebug);
			if(isDebug) System.out.println("本地ip--------" + ip); 
		} else if(wifiNetworkInfo.isConnected()) {
			WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
			WifiInfo wifiInfo = wifiManager.getConnectionInfo();
			int ipAddress = wifiInfo.getIpAddress();
			ip = intToip(ipAddress);
			if(isDebug) System.out.println("wifi_ip地址为------" + ip);
		}
	}
	// 如果连接的是移动网络， 第二步， 获取本地ip地址：getLocalIpAddress; 这样获取的是ipv4格式的ip地址
	private static String getLocalIpAddress_step2(boolean isDebug) {
		try {
			String ipv4;
			ArrayList<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
			for(NetworkInterface ni:nilist) 
			{
				ArrayList<InetAddress> ialist = Collections.list(ni.getInetAddresses());
				for(InetAddress address:ialist) 
				{
					if(!address.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipv4 = address.getHostAddress()) ) {
						return ipv4;
					}
				}
			}
		} catch (SocketException ex) {
			if(isDebug) System.out.println(ex.getMessage());
		}
		return null;
	}
	
	// 如果连接的是WI-FI网络，第三步WI-FI ip地址：intToIp(ipAddress);
	private static String intToip(int ipInt) {
		StringBuilder sb = new StringBuilder();
		sb.append(ipInt & 0xFF).append(".");
		sb.append((ipInt >>  8) & 0xFF).append(".");
		sb.append((ipInt >> 16) & 0xFF).append(".");
		sb.append((ipInt >> 24) & 0xFF);
		return sb.toString();
	}
	
	// 网上的很多代码获取的是ipv6的本地ip， 在微信支付里这种ip地址无法调起微信支付，附代码：
	private static String getlocalIp(boolean isDebug) {
		String ip;
		try {
			for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();en.hasMoreElements();) 
			{
				NetworkInterface intf = en.nextElement();
				for(Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) 
				{
					InetAddress inetAddress = enumIpAddr.nextElement();
					if(!inetAddress.isLoopbackAddress()&&!inetAddress.isLinkLocalAddress()) {
						ip=inetAddress.getHostAddress().toString();
						if(isDebug) System.out.println("ip======="+inetAddress.getHostAddress().toString());
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch(SocketException ex) {
			if(isDebug) System.out.println(ex.getMessage()); 
		}
		return null;
	}
	
	//========================================================
	//========================================================
	//========================================================
	//========================================================
	//========================================================
}
